﻿using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormModel.PhyQuery;
using Basic.FormRemoteModel;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class PhysicalQueryCollect : IPhysicalQueryCollect
    {
        private readonly IPhysicalQueryDAL _PhyQuery;

        public PhysicalQueryCollect ( IPhysicalQueryDAL phyQuery )
        {
            this._PhyQuery = phyQuery;
        }
        public long Add ( PhyQueryAdd data )
        {
            if ( this._PhyQuery.IsExists(c => c.FormId == data.FormId && c.Location == data.Location && c.Label == data.Label) )
            {
                throw new ErrorException("form.query.label.repeat");
            }
            return this._PhyQuery.Add(data);
        }
        public Result[] GetsByFormId<Result> ( long formId ) where Result : class, new()
        {
            return this._PhyQuery.Gets<Result>(a => a.FormId == formId, "Sort");
        }
        public Result[] GetsByFormId<Result> ( long formId, LayoutLocation location ) where Result : class, new()
        {
            return this._PhyQuery.Gets<Result>(a => a.FormId == formId && a.Location == location, "Sort");
        }
        public DBPhysicalQueryLayout Get ( long id )
        {
            return this._PhyQuery.Get(id);
        }
        public bool Update ( DBPhysicalQueryLayout source, PhyQuerySet set )
        {
            if ( source.Label != set.Label && this._PhyQuery.IsExists(c => c.FormId == source.FormId && c.Location == source.Location && c.Label == set.Label) )
            {
                throw new ErrorException("form.query.label.repeat");
            }
            return this._PhyQuery.Update(source, set);
        }
        public void Delete ( DBPhysicalQueryLayout obj )
        {
            this._PhyQuery.Delete(obj.Id);
        }
        public void Clear ( long formId )
        {
            long[] ids = this._PhyQuery.Gets(a => a.FormId == formId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._PhyQuery.Delete(ids);
            }
        }

        public void SetSort ( KeyValuePair<long, int>[] sets )
        {
            this._PhyQuery.SetSort(sets);
        }
    }
}
